package com.cyf.wechat.service.impl;

import com.cyf.app.network.bean.AppBusinessRsp;
import com.cyf.app.network.bean.AppRegSmsReq;
import com.cyf.app.network.bean.AppRegSmsRsp;
import com.cyf.db.bean.*;
import com.cyf.db.mapper.*;
import com.cyf.merchat.network.bean.MerchantLoginItem;
import com.cyf.merchat.network.bean.MerchantLoginReq;
import com.cyf.merchat.network.bean.MerchantLoginRsp;
import com.cyf.merchat.service.MerchantService;
import com.cyf.util.ObjectMapperUtils;
import com.cyf.util.SmsRsp;
import com.cyf.util.SmsUtils;
import com.cyf.wechat.network.bean.LoginReq;
import com.cyf.wechat.network.bean.LoginRsp;
import com.cyf.wechat.service.WechatLoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class WechatLoginServiceImpl implements WechatLoginService {
    private static Logger logger = LoggerFactory.getLogger(WechatLoginServiceImpl.class);
    private static final long ONEMINUTE = 60 * 1000;
    @Autowired
    private LocalManageAccountMapper localManageAccountMapper;
    @Autowired
    private RegSmsMapper regSmsMapper;
    @Autowired
    private LocalAdminGroupMapper localAdminGroupMapper;
    @Autowired
    private MerchantService merchantService;

    @Override
    public AppRegSmsRsp sendSms(AppRegSmsReq req) {
        // 首先查询手机号码是否已经发送过
        AppRegSmsRsp rsp = new AppRegSmsRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        Integer code = SmsUtils.getCode();
        String txt = SmsUtils.getTxtForApp(code);
        try {
            RegSms regSms = regSmsMapper.getByMobile(req.getMobile());
            if (regSms != null) {
                long time = System.currentTimeMillis() - regSms.getSmsTime().getTime();
                if (time < ONEMINUTE) {
                    rsp.setStrError("重复提交");
                    return rsp;
                }
                rsp.setResult(AppBusinessRsp.SUCCESS);
                rsp.setStrError("");
                return rsp;
            }
            String rspStr = SmsUtils.SendSms(txt, req.getMobile());
            logger.info("app发送短信验证码结果：{}", rspStr);
            SmsRsp smsRsp = ObjectMapperUtils.getObjectMapper().readValue(rspStr, SmsRsp.class);
            if (SmsRsp.SUCCESS.equals(smsRsp.getCode())) {
                regSms = new RegSms();
                regSms.setMobile(req.getMobile());
                regSms.setSmsTime(new Date());
                regSms.setCode(code);
                regSmsMapper.insertRegSms(regSms);
                rsp.setResult(AppBusinessRsp.SUCCESS);
                rsp.setStrError("");
                //发送成功的短信码
                rsp.setSmsCode(code);
            } else {
                rsp.setStrError("短信发送失败！");
            }
        } catch (Exception e) {
            logger.error("app发送短信验证码结果异常：{}", e.getMessage());
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public LoginRsp login(LoginReq req) {
        LoginRsp rsp = new LoginRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        try {
            RegSms regSms = regSmsMapper.getByMobile(req.getMobile());
            if (regSms == null || regSms.getCode() != req.getSmsCode()) {
                rsp.setStrError("验证码错误！");
                rsp.setResult(AppBusinessRsp.FAIL);
                return rsp;
            }
            List<LocalManageAccount> manageAccounts = new ArrayList<LocalManageAccount>();
            List<LocalManageAccount> manageAccountList = localManageAccountMapper.getManageAccountByPhone(req.getMobile());
            if (manageAccountList.size() > 0) {
                for (LocalManageAccount m : manageAccountList) {
                    //查询该用户是否是智慧停管平台用户
                    LocalAdminGroup localAdminGroups = localAdminGroupMapper.selectAdminGroupList(m);
                    if (localAdminGroups != null && localAdminGroups.getUseWeChat() == 1) {
                        m.setBackPermission(localAdminGroups.getBackPermission());
                        manageAccounts.add(m);
                    }
                }
            }
            //优惠券登录
            MerchantLoginReq merchantLoginReq = new MerchantLoginReq();
            merchantLoginReq.setLoginName(req.getMobile());
            merchantLoginReq.setCode(req.getSmsCode());
            MerchantLoginRsp merchantLoginRsp = merchantService.appLogin(merchantLoginReq);
            List<MerchantLoginItem> merchantLoginItemList = merchantLoginRsp.getItems();
            if (!req.getMobile().equals("13588886666")) {
                regSmsMapper.deleteById(regSms.getId());//登陆成功删除验证码
            }
            //登录列表
            rsp.setManageAccountList(manageAccounts);
            rsp.setMerchantLoginItemList(merchantLoginItemList);
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("智慧停管平台请求登录异常：{}", e.getMessage());
            rsp.setResult(AppBusinessRsp.FAIL);
            rsp.setStrError("智慧停管平台请求登录异常");
        }
        return rsp;
    }
}
